package top.java.multithreading;


import java.util.concurrent.locks.ReentrantLock;

/**
 *
 *          线程的同步测试题    账户存钱
 *
 */


public class ThreadTest8 {

    public static void main(String[] args) {
        Account account = new Account(0);
        Customer customer = new Customer(account);
        Thread t1 = new Thread(customer);
        Thread t2 = new Thread(customer);
        t1.setName("账户1");
        t2.setName("账户2");
        t1.start();
        t2.start();
    }

}

class Account{

    private int balance;

    public Account(int balance) {
        this.balance = balance;
    }

    public void setBalance(int atm) {
        if (atm > 0) {
            this.balance += atm;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ":存钱成功，余额为：" + balance);
        }else {
            System.out.println("存钱失败");
        }
    }
}

class Customer implements Runnable{

    private Account account;

    private ReentrantLock lock = new ReentrantLock(true);

    public Customer(Account account) {
        this.account = account;
    }

    @Override
    public void run() {
        for (int i = 0;i < 3;i++) {
            try {
                lock.lock();
                account.setBalance(1000);
            }finally {
                lock.unlock();
            }
        }
    }

}
